package dao;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.StringBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryCursor;
import com.sleepycat.je.Transaction;

public class MessageDAO extends CommonDAO {

	private MessageBinding binding = null;
	public MessageDAO(String dbName) {
		this("/tmp/db/MESSAGE.DB", dbName);
	}
	
	public MessageDAO(String envDir, String dbName) {
		super(envDir, dbName);
		binding = new MessageBinding();
	}

	public <Message> boolean set(List<Message> params){

		
        boolean result = false;
        for(Message m : params){
        	DatabaseEntry dataEntry = new DatabaseEntry();
        	DatabaseEntry keyEntry;
			try {
				keyEntry = new DatabaseEntry(((dao.Message) m).getTo().getBytes());
				binding.objectToEntry(m, dataEntry);	        	
	    		OperationStatus status = 
	    				this.db.put(txn, keyEntry, dataEntry);
	    		if(status == OperationStatus.SUCCESS){
	    			result = true;
	    			System.out.println( ((dao.Message) m).getTo()+":"+ ((dao.Message) m).getFrom()+":"+status + " result is " + result);
	    		}
	    			
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
		txn.commit();
		return result;
	}

	public List<Message> get(String strKey){
		List<Message> ret = new ArrayList<Message>();
		Cursor secCursor = null;
		
        try {
        	 DatabaseEntry searchKey =
                     new DatabaseEntry(strKey.getBytes());
             DatabaseEntry foundData = new DatabaseEntry();
             secCursor = this.db.openCursor(null, null);

             while(secCursor.getNext(searchKey, foundData,
                     LockMode.DEFAULT) == OperationStatus.SUCCESS){
            	 System.out.println(foundData.getSize());
            	 Message message = (Message)binding.entryToObject(foundData);
            	 ret.add( message );
             }
	        
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			secCursor.close();
		}
		return ret;
	}
	
	public boolean delete(Message m){
		boolean ret = false;
		try{
			DatabaseEntry key = new DatabaseEntry(m.getTo().getBytes());
			OperationStatus status = db.delete(null, key);
			ret = status == OperationStatus.SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			txn.commit();
		}
		return ret;			
	}
}
